package com.android.kotlincoroutinemvvmdemo
import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.android.kotlincoroutinemvvmdemo.base.BaseActivity
import com.android.kotlincoroutinemvvmdemo.viewmodel.FlowUseViewModel
import com.android.kotlincoroutinemvvmdemo.databinding.ActivityFlowCaseBinding
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flatMapConcat
import kotlinx.coroutines.launch

class FlowCaseActivity : BaseActivity<ActivityFlowCaseBinding>() {

    private lateinit var mViewModel : FlowUseViewModel

    override fun getLayoutId() = R.layout.activity_flow_case

    override fun init(savedInstanceState: Bundle?) {

        mViewModel = ViewModelProvider(this)[FlowUseViewModel::class.java]

        mBinding.btnSharedFlow.setOnClickListener {
            lifecycleScope.launch {
                mViewModel.flowConvertSharedFlow.collect {
                    Log.d(Constants.TAG, it)
                }
            }
        }

        mBinding.btnStateFlow.setOnClickListener {
            lifecycleScope.launch {
                mViewModel.flowConvertStateFlow.collect {
                    Log.d(Constants.TAG, it)
                }
            }
        }

        mBinding.btnSuspendCancelable.setOnClickListener {
            lifecycleScope.launch {
                val result = mViewModel.suspendCancellableData()
                Log.d(Constants.TAG,"result---${result}")
            }
        }

        mBinding.btnCallbackFlow.setOnClickListener {
            lifecycleScope.launch {
                mViewModel.getSearchCallbackFlow().flatMapConcat {
                    mViewModel.getDesCallbackFlow(it)
                }.collect {
                    Log.d(Constants.TAG,"search---${it}")
                }
            }

            //广播跨进程通信
            //sendBroadcast(Intent(Constants.ACTION_IPC))
        }

        Log.d(Constants.TAG, "FlowCaseActivity---onCreate---processId:${android.os.Process.myPid()}")
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.d(Constants.TAG,"||onDestroy---search---onDestroy||")
        //val data = 10 / 0

        //获取pid,销毁进程
        val pid = android.os.Process.myPid()
        android.os.Process.killProcess(pid)
    }
}